<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>GeoNexus 数据中台 - CesiumJS 三维测试客户端</title>
    <!-- 引入 CesiumJS -->
    <script src="https://cesium.com/downloads/cesiumjs/releases/1.114/Build/Cesium/Cesium.js"></script>
    <link href="https://cesium.com/downloads/cesiumjs/releases/1.114/Build/Cesium/Widgets/widgets.css" rel="stylesheet">
    <!-- 自定义样式 -->
    <style>
        html, body, #cesiumContainer {
            width: 100%;
            height: 100%;
            margin: 0;
            padding: 0;
            overflow: hidden;
        }
        
        .control-panel {
            position: absolute;
            top: 10px;
            left: 10px;
            z-index: 1;
            background-color: rgba(255, 255, 255, 0.8);
            padding: 10px;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
            max-width: 300px;
        }
        
        .control-panel h3 {
            margin-top: 0;
            margin-bottom: 10px;
            color: #1a73e8;
        }
        
        .control-panel select, .control-panel button {
            width: 100%;
            margin-bottom: 10px;
            padding: 8px;
            border: 1px solid #ccc;
            border-radius: 4px;
        }
        
        .control-panel button {
            background-color: #1a73e8;
            color: white;
            border: none;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        
        .control-panel button:hover {
            background-color: #1557b0;
        }
        
        .info-panel {
            position: absolute;
            top: 10px;
            right: 10px;
            z-index: 1;
            background-color: rgba(255, 255, 255, 0.8);
            padding: 10px;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
            max-width: 300px;
            max-height: 80%;
            overflow-y: auto;
            display: none;
        }
        
        .info-panel h3 {
            margin-top: 0;
            margin-bottom: 10px;
            color: #1a73e8;
        }
        
        .info-panel table {
            width: 100%;
            border-collapse: collapse;
        }
        
        .info-panel th, .info-panel td {
            padding: 5px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }
        
        .info-panel th {
            font-weight: bold;
        }
        
        .media-container {
            margin-top: 10px;
        }
        
        .media-container img {
            max-width: 100%;
            margin-bottom: 10px;
        }
        
        .loading {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background-color: rgba(0, 0, 0, 0.7);
            color: white;
            padding: 15px 30px;
            border-radius: 5px;
            font-size: 18px;
            z-index: 2;
            display: none;
        }
    </style>
</head>
<body>
    <!-- Cesium 容器 -->
    <div id="cesiumContainer"></div>
    
    <!-- 控制面板 -->
    <div class="control-panel">
        <h3>GeoNexus 数据中台</h3>
        <select id="dataSourceSelect">
            <option value="">-- 选择数据源 --</option>
            <optgroup label="PostGIS Enterprise Provider">
                <option value="/provider-postgis-enterprise/public.business_features">业务要素</option>
                <option value="/provider-postgis-enterprise/public.buildings">建筑</option>
                <option value="/provider-postgis-enterprise/public.pois">兴趣点</option>
            </optgroup>
            <optgroup label="DTS Provider">
                <option value="/provider-dts/buildings">建筑</option>
                <option value="/provider-dts/pois">兴趣点</option>
                <option value="/provider-dts/default">默认场景</option>
            </optgroup>
        </select>
        <button id="loadDataBtn">加载数据</button>
        <button id="clearDataBtn">清除数据</button>
    </div>
    
    <!-- 信息面板 -->
    <div class="info-panel" id="infoPanel">
        <h3>要素信息</h3>
        <div id="featureInfo"></div>
        <div id="mediaContainer" class="media-container"></div>
    </div>
    
    <!-- 加载提示 -->
    <div class="loading" id="loadingIndicator">数据加载中...</div>
    
    <!-- 脚本 -->
    <script>
        // 使用公共令牌 - 仅用于开发测试
        Cesium.Ion.defaultAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI5N2UyMjcwOS00MDY1LTQxYjEtYjZjMy00YTU0ZTg5MmViYWQiLCJpZCI6ODAzMDYsImlhdCI6MTY0Mjc0ODI2MX0.dkwAL1CcljUV7NA7fDbhXXnmyZQU_c-G5zRx8PtEcxE';
        
        // 创建 Cesium Viewer，使用 OpenStreetMap 作为底图
        const viewer = new Cesium.Viewer('cesiumContainer', {
            baseLayerPicker: false, // 禁用底图选择器
            geocoder: false, // 禁用地理编码器
            homeButton: false, // 禁用主页按钮
            sceneModePicker: false, // 禁用场景模式选择器
            navigationHelpButton: false, // 禁用导航帮助按钮
            animation: false, // 禁用动画控件
            timeline: false, // 禁用时间线控件
            fullscreenButton: false, // 禁用全屏按钮
            infoBox: false, // 禁用信息框
            imageryProvider: new Cesium.OpenStreetMapImageryProvider({
                url: 'https://a.tile.openstreetmap.org/'
            })
        });
        
        // 移除版权信息
        viewer.cesiumWidget.creditContainer.style.display = 'none';
        
        // 设置初始视图 - 中国中部
        viewer.camera.flyTo({
            destination: Cesium.Cartesian3.fromDegrees(116.4, 39.9, 1000000),
            orientation: {
                heading: 0.0,
                pitch: -Cesium.Math.PI_OVER_TWO,
                roll: 0.0
            }
        });
        
        // 获取DOM元素
        const dataSourceSelect = document.getElementById('dataSourceSelect');
        const loadDataBtn = document.getElementById('loadDataBtn');
        const clearDataBtn = document.getElementById('clearDataBtn');
        const infoPanel = document.getElementById('infoPanel');
        const featureInfo = document.getElementById('featureInfo');
        const mediaContainer = document.getElementById('mediaContainer');
        const loadingIndicator = document.getElementById('loadingIndicator');
        
        // 当前加载的数据源
        let currentDataSource = null;
        
        // 加载数据按钮点击事件
        loadDataBtn.addEventListener('click', async () => {
            const serviceUrl = dataSourceSelect.value;
            
            if (!serviceUrl) {
                alert('请选择一个数据源');
                return;
            }
            
            // 清除之前的数据
            clearData();
            
            // 显示加载指示器
            loadingIndicator.style.display = 'block';
            
            try {
                await loadDataFromKoop(serviceUrl);
            } finally {
                // 隐藏加载指示器
                loadingIndicator.style.display = 'none';
            }
        });
        
        // 清除数据按钮点击事件
        clearDataBtn.addEventListener('click', () => {
            clearData();
        });
        
        // 从Koop加载数据
        async function loadDataFromKoop(serviceUrl) {
            try {
                // 构建查询URL，请求GeoJSON格式
                const queryUrl = `${serviceUrl}/FeatureServer/0/query?f=geojson&where=1=1&outFields=*`;
                
                console.log('正在请求数据:', queryUrl);
                
                const response = await fetch(queryUrl);
                
                if (!response.ok) {
                    throw new Error(`HTTP错误 ${response.status}: ${await response.text()}`);
                }
                
                const geojsonData = await response.json();
                
                console.log('数据加载成功:', geojsonData);
                
                if (!geojsonData.features || geojsonData.features.length === 0) {
                    alert('没有找到任何要素');
                    return;
                }
                
                // 使用Cesium的GeoJsonDataSource加载数据
                const dataSource = await Cesium.GeoJsonDataSource.load(geojsonData, {
                    stroke: Cesium.Color.HOTPINK,
                    fill: Cesium.Color.PINK.withAlpha(0.5),
                    strokeWidth: 3,
                    markerSymbol: '📍'
                });
                
                // 将数据源添加到viewer中
                viewer.dataSources.add(dataSource);
                currentDataSource = dataSource;
                
                // 自动缩放到数据显示范围
                viewer.flyTo(dataSource);
                
                // 为每个实体添加点击事件
                setupEntityClickHandlers(dataSource);
                
                console.log('数据渲染完成');
            } catch (error) {
                console.error('从Koop加载数据失败:', error);
                alert(`加载数据失败: ${error.message}`);
            }
        }
        
        // 清除数据
        function clearData() {
            if (currentDataSource) {
                viewer.dataSources.remove(currentDataSource);
                currentDataSource = null;
            }
            
            // 隐藏信息面板
            infoPanel.style.display = 'none';
        }
        
        // 设置实体点击事件处理
        function setupEntityClickHandlers(dataSource) {
            // 监听选中实体变化事件
            viewer.selectedEntityChanged.addEventListener(async (selectedEntity) => {
                if (selectedEntity) {
                    displayEntityInfo(selectedEntity);
                } else {
                    // 隐藏信息面板
                    infoPanel.style.display = 'none';
                }
            });
        }
        
        // 显示实体信息
        function displayEntityInfo(entity) {
            if (!entity || !entity.properties) {
                return;
            }
            
            // 显示信息面板
            infoPanel.style.display = 'block';
            
            // 获取实体属性
            const properties = entity.properties;
            
            // 构建HTML表格显示属性
            let tableHtml = '<table>';
            
            // 遍历所有属性
            for (const key in properties) {
                if (properties.hasOwnProperty(key) && key !== 'asset_ids') {
                    const value = properties[key]._value || properties[key];
                    tableHtml += `<tr><th>${key}</th><td>${value}</td></tr>`;
                }
            }
            
            tableHtml += '</table>';
            featureInfo.innerHTML = tableHtml;
            
            // 检查是否有关联的资产ID
            if (properties.asset_ids && properties.asset_ids._value) {
                loadAssetMedia(properties.asset_ids._value);
            } else {
                mediaContainer.innerHTML = '<p>没有关联媒体资产</p>';
            }
        }
        
        // 加载资产媒体
        async function loadAssetMedia(assetIds) {
            try {
                mediaContainer.innerHTML = '<p>正在加载媒体资产...</p>';
                
                // 如果assetIds是字符串，尝试解析为数组
                if (typeof assetIds === 'string') {
                    try {
                        assetIds = JSON.parse(assetIds);
                    } catch (e) {
                        assetIds = [assetIds];
                    }
                }
                
                if (!Array.isArray(assetIds)) {
                    assetIds = [assetIds];
                }
                
                // 这里应该调用DAM服务API获取资产信息
                // 由于我们没有实际的DAM服务，这里模拟一些示例媒体
                const mediaHtml = assetIds.map(id => {
                    // 模拟不同类型的媒体
                    if (id.includes('asset1')) {
                        return `<img src="https://via.placeholder.com/300x200?text=资产ID:${id}" alt="资产 ${id}">`;
                    } else if (id.includes('asset2')) {
                        return `<video width="100%" controls><source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">您的浏览器不支持视频标签</video>`;
                    } else {
                        return `<div style="padding: 10px; background-color: #f0f0f0; margin-bottom: 10px;">资产 ${id} (文档)</div>`;
                    }
                }).join('');
                
                mediaContainer.innerHTML = mediaHtml || '<p>没有可显示的媒体</p>';
            } catch (error) {
                console.error('加载媒体资产失败:', error);
                mediaContainer.innerHTML = `<p>加载媒体资产失败: ${error.message}</p>`;
            }
        }
    </script>
</body>
</html>